package com.hanxiaozhang.threadbase2ndedition.no4threadend;

import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用Volatile标识，停止线程〉
 *  弊端：如果线程阻塞，将不能停止
 *
 * @author hanxinghua
 * @create 2021/11/3
 * @since 1.0.0
 */
public class No3VolatileFlag {

    private static volatile boolean running = true;

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            long i = 0L;

            while (running) {
                i++;
                // 模拟阻塞
                if (i > 10000) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("end and i = " + i);
        });

        t.start();
        TimeUnit.SECONDS.sleep(1);

        running = false;
    }

}
